﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.PreProduction;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.PreProductionCommandHandler
{
    /// <summary>
    /// 添加预生产计划命令处理器
    /// </summary>
    public class PreProductionCommandHandler : IRequestHandler<PreProductionCreateCommand, int>
    {
        private readonly IPreProducsRepository _preProducsRep;
        private readonly IPreProductionRepository _preProductionRep;
        private readonly ISqlSugarClient db;
        private readonly IMapper _mapper;

        public PreProductionCommandHandler(IPreProducsRepository preProducsRep, IPreProductionRepository preProductionRep, ISqlSugarClient db, IMapper mapper)
        {
            this._preProducsRep = preProducsRep;
            this._preProductionRep = preProductionRep;
            this.db = db;
            this._mapper = mapper;
        }

        public async Task<int> Handle(PreProductionCreateCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                // 将请求数据映射到实体
                var purchaseContract = _mapper.Map<PreProduction>(request.addDto);

                // 插入预生产计划
                int contractId = await _preProductionRep.AddAsync(purchaseContract);

                // 假设需要插入相关的预生产产品信息
                foreach (var item in request.addDto.Adddtos)
                {
                    PreProducs detail = new PreProducs
                    {
                        PPDocuNumber = purchaseContract.PPDocuNumber,
                        ProductId = item.ProductId,
                        PPsNum = item.PPsNum,
                        PPsDeliveryDate = item.PPsDeliveryDate,
                        PNumber = item.PNumber,
                        PName = item.PName,
                        PSpec = item.PSpec,
                        PUnit = item.PUnit,
                        PPsSmark = item.PPsSmark,
                        AddName = purchaseContract.AddName,
                        AddTime = purchaseContract.AddTime,
                        Office_Id = purchaseContract.Office_Id,
                        User_Id = purchaseContract.User_Id
                    };

                    await _preProducsRep.AddAsync(detail);
                }

                // 提交事务
                db.Ado.CommitTran();

                return 1; 
            }
            catch (Exception ex)
            {
                // 捕获异常并回滚事务
                db.Ado.RollbackTran();
                // 可以记录日志以便调试
                throw new Exception("事务失败，已回滚所有操作", ex);
            }
        }
    }
}
